package com.test.netty.nettyhb;


import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
public class HeartBeatHandler extends SimpleChannelInboundHandler<String> {

    private int readIdleTimes = 0;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        log.info(" ====== > [server] message received : " + msg);
        if ("I am alive".equals(msg)) {
            ctx.channel().writeAndFlush("copy that");
        } else {
            log.info(" 其他信息处理 ... ");
            ctx.fireChannelRead(msg);
        }
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        IdleStateEvent event = (IdleStateEvent) evt;
        String eventType = null;
        switch (event.state()) {
            case READER_IDLE:
                String now = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime());
                eventType = "读空闲";
                readIdleTimes++; // 读空闲的计数加1
                log.info(String.format("READER IDLE Time:[%s]", now));
                break;
            case WRITER_IDLE:
                eventType = "写空闲";
                // 不处理
                break;
            case ALL_IDLE:
            default:
                eventType = "读写空闲";
                // 不处理
                break;
        }
        log.info(ctx.channel().remoteAddress() + "超时事件：" + eventType);
        log.info("====>readIdleTimes:" + readIdleTimes);
        if (readIdleTimes > 3) {
            log.info(" [server]读空闲超过3次，关闭连接");
            ctx.channel().writeAndFlush("you are out");
            ctx.channel().close();
        }
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("=== " + ctx.channel().remoteAddress() + " is active ===");
    }
}
